package com.yuntongxun.ecdemo.voicechat.presenter.impl;

import android.content.Context;


import com.loopj.android.http.RequestParams;
import com.yuntongxun.ecdemo.voicechat.api.ApiConstants;
import com.yuntongxun.ecdemo.voicechat.interactor.ICommonRequestInteractor;
import com.yuntongxun.ecdemo.voicechat.interactor.impl.CommonRequestInteractorImpl;
import com.yuntongxun.ecdemo.voicechat.listeners.IRequestListener;
import com.yuntongxun.ecdemo.voicechat.presenter.ICommonRequestPresenter;
import com.yuntongxun.ecdemo.voicechat.util.http.HttpStatusUtil;
import com.yuntongxun.ecdemo.voicechat.util.iview.ICommonViewUi;

import org.json.JSONObject;

import java.io.File;
import java.util.Map;

/**
 * Created by liucanwen on 16/1/23.
 */
public class CommonRequestPresenterImpl implements ICommonRequestPresenter, IRequestListener {

    public Context context;

    public ICommonViewUi iCommonViewUi;

    public ICommonRequestInteractor iCommonRequestInteractor;

    public CommonRequestPresenterImpl(Context context, ICommonViewUi iCommonViewUi) {

        this.context = context;
        this.iCommonViewUi = iCommonViewUi;
        iCommonRequestInteractor = new CommonRequestInteractorImpl(this);
    }

    @Override
    public void request(int eventTag, Context context, String url, RequestParams params) {

        iCommonRequestInteractor.request(eventTag, context, url, params);
    }

    @Override
    public void upload(int eventTag, Context context, String url, String[] fileKeys, File[] files, Map<String, String> params) {
        iCommonRequestInteractor.upload(eventTag, context, url, fileKeys, files, params);
    }

    @Override
    public void onSuccess(int eventTag, String data) {
        if (HttpStatusUtil.getStatus(data)) {
            iCommonViewUi.getRequestData(eventTag, data);
        } else {

            if(eventTag == ApiConstants.EventTags.VERSION_UPDATE) {

                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int statusCode = jsonObject.getInt("statusCode");

                    if (statusCode==3) {
                        iCommonViewUi.getRequestData(eventTag, data);
                    }
                } catch (Exception ex) {
                    iCommonViewUi.onRequestSuccessException(eventTag, HttpStatusUtil.getStatusMsg(data));
                }

            }else{
                iCommonViewUi.onRequestSuccessException(eventTag, HttpStatusUtil.getStatusMsg(data));
            }
        }
    }

    @Override
    public void onError(int eventTag, String msg) {
        iCommonViewUi.onRequestFailureException(eventTag, msg);
    }

    @Override
    public void isRequesting(int eventTag, boolean status) {
        iCommonViewUi.isRequesting(eventTag, status);
    }
}
